package cn.tworice.upload.web;

import cn.tworice.common.annotation.NoEncryption;
import cn.tworice.upload.service.DownloadService;
import cn.tworice.upload.service.UploadService;
import cn.tworice.common.vo.RequestResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.util.List;

@RestController
@RequestMapping("admin/upload")
@Slf4j
@CrossOrigin
@Api(tags = "文件上传")
public class UploadController {

    @Resource
    private UploadService uploadService;

    /**
     * 快捷上传文件接口
     * 返回上传后的地址
     *
     */
    @PostMapping("upload")
    @ApiOperation("文件上传接口")
    @NoEncryption
    public RequestResult upload(MultipartFile file, String agent) {
        String path = uploadService.uploadFile(file);
        if (path != null) {
            return RequestResult.success("上传成功")
                    .appendData("url", agent + "/receive/preview/" + path)
                    .appendData("downloadUrl", agent + "/receive/fetch/" + path)
                    .appendData("file", path)
                    .appendData("message", "访问时请在该文件路径前加上本服务器地址");
        } else {
            return RequestResult.error("上传失败");
        }
    }

    @PostMapping("uploadInducts")
    @ApiOperation("文件上传接口")
    @NoEncryption
    public RequestResult uploadInducts(MultipartFile[] files) {
        List<String> paths = uploadService.uploadFiles(files);
        return RequestResult.success("上传成功").appendData("files", paths.toString());
    }

    /**
     * 快捷上传文件接口
     * 返回上传后的地址
     * @author 二饭[tworice@sina.cn][2022/3/2 14:02]
     */
    @PostMapping("uploadToDir")
    @ApiOperation("上传文件到指定目录")
    @NoEncryption
    public RequestResult uploadToDir(MultipartFile file, @RequestParam("dir") String dir) {
        String path = uploadService.uploadFileToDir(file, dir);
        if(path!=null){
            return RequestResult.success("上传成功")
                    .appendData("file",path)
                    .appendData("message", "访问时请在该文件路径前加上本服务器地址");
        }else{
            return RequestResult.error("上传失败");
        }
    }
}
